package org.ihelpuoo.weboo.tag.core;

import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.Tag;

import org.ihelpuoo.lang.StringUtils;
import org.ihelpuoo.parser.segment.Segment;
import org.ihelpuoo.weboo.tag.WebooTag;

public class GasketTag extends WebooTag
{

	private static final long	serialVersionUID	= 1810102669045133689L;

	private List<Segment>		values;

	private String				to;

	public String getTo()
	{
		return to;
	}

	public void setTo(String to)
	{
		this.to = to;
	}

	void setContent(Segment seg)
	{
		values.add(seg);
	}

	@Override
	protected void start() throws JspException
	{
		values = new LinkedList<Segment>();
	}

	@Override
	protected void end() throws JspException
	{
		Tag p = null;
		if (values.size() == 0)
		{
			String s = getBodyContent().getString();
			if (!StringUtils.isEmpty(s))
			{
				p = _findParentViewTag();
				((ViewTag)p).getSegment().add(to,s);
			}
		}
		else
		{
			p = _findParentViewTag();
			Iterator<Segment> it = values.iterator();
			while (it.hasNext())
				((ViewTag)p).getSegment().add(to,it.next());
		}
	}

	private Tag _findParentViewTag() throws JspException
	{
		Tag p;
		p = this.getParent();
		while (p != null && !(p instanceof ViewTag))
			p = p.getParent();
		if (p == null)
			throw new JspException("Lack pattern View for GasketTag!");
		return p;
	}

}
